import django_filters
from .models import Goods
from django.db.models import Q
from django_filters import rest_framework as filters


class GoodsFilter(filters.FilterSet):
    """
    商品过滤类
    """
    pricemin = django_filters.NumberFilter(field_name='shop_price', lookup_expr='gte', help_text='最低价')
    pricemax = django_filters.NumberFilter(field_name='shop_price', lookup_expr='lte', help_text='最高价')
    top_category = django_filters.NumberFilter(method='top_category_filter', help_text='父类ID')

    def top_category_filter(self, queryset, name, value):
        return queryset.filter(Q(category_id=value) | Q(category__parent_category_id=value) | Q(
            category__parent_category__parent_category_id=value)).order_by('-id')

    class Meta:
        model = Goods
        fields = ['pricemin', 'pricemax', 'top_category', 'is_hot', 'is_new']
